package com.zrrd.straw1.service.impl;

import com.zrrd.straw1.entity.Comment;
import com.zrrd.straw1.entity.User;
import com.zrrd.straw1.mapper.CommentMapper;
import com.zrrd.straw1.mapper.UserMapper;
import com.zrrd.straw1.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.straw1.vo.CommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zrrd
 * @since 2024-03-03
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    CommentMapper commentMapper;

    /**
     * 保存评论内容！
     * 调用用户查询的服务 ！
     *
     * @param commentVo
     * @param username
     * @return
     */
    @Override
    public Comment saveComment( CommentVo commentVo,String username) {
        // 在当前的业务层面中，需要使用其它业务线的功能或服务 。
        User user = userMapper.findUserByUsername(username);

        // 整理评论信息内容 ！
        Comment comment = new Comment()
                .setUserId( user.getId())
                .setUserNickName( user.getNickName())
                .setAnswerId( commentVo.getAnswerId())
                .setContent(commentVo.getContent())
                .setGmtCreate( LocalDateTime.now())
                .setGmtModified( LocalDateTime.now());
        int num = commentMapper.insert( comment );
        if( num != 1) throw ServiceException.busy();
        // 实时回显添加信息
        return comment ;
    }

    @Override
    public boolean removeComment(Integer commentId, String username) {

        //鉴权,判断是不是讲师，是不是发布者
        User user = userMapper.findUserByUsername(username);
        //如果是教师，可以删除
        if( user.getAccountType() != null && user.getAccountType() == 1){
            int i = commentMapper.deleteById(commentId);
            return i == 1 ;
        }

        //如果不是教师，再判断是不是发布者
        Comment comment = commentMapper.selectById(commentId);
        if( comment.getUserId() == user.getId() ){
            int i = commentMapper.deleteById(commentId);
            return i == 1 ;
        }

        throw ServiceException.invalidRequest("权限不足");
    }

    @Override
    public Comment updateComment(Integer commentId, CommentVo commentVo, String username) {
        //1.鉴权
        User user = userMapper.findUserByUsername(username);
        Comment comment = commentMapper.selectById( commentId );
                            //逻辑运算符连接多个判断条件！
        if( user.getAccountType()!= null && user.getAccountType() == 1 || user.getId() == comment.getUserId()){
            //修改评论内容
          comment.setContent(commentVo.getContent());
          int num = commentMapper.updateById(comment);
          if(num!=1)throw ServiceException.busy();
          return comment;
        }
        return null;
    }
}
